﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Collections;
using System.Collections.Generic;
using System.IO.Ports;
using System.Threading;



namespace Dt261.help
{




/// <summary>
/// 转盘监听，
/// 传输结果，监听线程，
/// </summary>
public static class ConnectTurntable
{
    //监听串口线程
    static Thread dataReceiveThread_1, dataReceiveThread_2;



    static SerialPort serialPort = new SerialPort();

    public static void StartSerialPortListen()
    {
        //设定
        serialPort.PortName = "COM1";
        serialPort.BaudRate = 1000;//设置串行波特率
            serialPort.ReadTimeout = 500;
        serialPort.WriteTimeout = 500;
        serialPort.DataReceived += null;

        //不使用DataReceived，自己写线程监听
        //开启线程监听串口
        try
        {
                string xuanzhuan="";
            //串口数据解析方法(忽视第二个参数，根据自己的解析方式自己写，这里放一个公司的串口解析)
            dataReceiveThread_1 = new Thread(() => DataReceiveFunction(serialPort, xuanzhuan));
            if (dataReceiveThread_1 != null && dataReceiveThread_1.IsAlive)
            {
                dataReceiveThread_1.Abort();
            }
            dataReceiveThread_1.Start();
        }
        catch (Exception ex)
        {
           // Debug.LogError("监听事件打开失败！ex=" + ex.Message);
        }
    }





    #region 串口数据解析
    static void DataReceiveFunction(SerialPort serialPort, string sensorResult)
    {
        try
        {
            /** **/
            byte[] RxBuffer = new byte[1000];
            UInt16 usRxLength = 0;

            int bytes = 0;
            int flag0 = 0xFF;
            int flag1 = 0xAA;
            int index = 0;//用于记录此时的数据次序
            while (true)
            {
                if (serialPort != null && serialPort.IsOpen)
                {
                    try
                    {
                        byte[] byteTemp = new byte[1000];

                        try
                        {
                            UInt16 usLength = 0;
                            try
                            {
                                usLength = (UInt16)serialPort.Read(RxBuffer, usRxLength, 700);
                            }
                            catch (Exception err)
                            {
                                //MessageBox.Show(err.Message);
                                //return;
                               // Debug.LogError("spSerialPort.Read！！ ex=" + err.Message);
                            }
                            usRxLength += usLength;
                            while (usRxLength >= 11)
                            {
                                //UpdateData Update = new UpdateData(DecodeData);
                                RxBuffer.CopyTo(byteTemp, 0);
                                if (!((byteTemp[0] == 0x55) & ((byteTemp[1] & 0x50) == 0x50)))
                                {
                                    for (int i = 1; i < usRxLength; i++) RxBuffer[i - 1] = RxBuffer[i];
                                    usRxLength--;
                                    continue;
                                }
                                if (((byteTemp[0] + byteTemp[1] + byteTemp[2] + byteTemp[3] + byteTemp[4] + byteTemp[5] + byteTemp[6] + byteTemp[7] + byteTemp[8] + byteTemp[9]) & 0xff) == byteTemp[10])
                                {
                                    Thread t = new Thread(() => XuanzhuanReceiveData(byteTemp, sensorResult));
                                    t.Start();
                                }
                                for (int i = 11; i < usRxLength; i++) RxBuffer[i - 11] = RxBuffer[i];
                                usRxLength -= 11;
                            }

                            Thread.Sleep(10);
                        }
                        finally
                        {

                        }
                    }
                    catch (Exception ex)
                    {
                        // Debug.Log(ex.Message);
                    }
                }
                Thread.Sleep(100);
            }
        }
        catch (Exception ex)
        {

            //log.Error("DataReceiveFunction！！ ex=" + ex.Message);
        }
    }






    private static void XuanzhuanReceiveData(byte[] RxBuffer, string sensorResult)
    {
        try
        {
            DecodeData( sensorResult, RxBuffer);
        }
        catch (Exception ex)
        {
            //NLog(" ComReceiveData ex={0}" + ex.Message);
        }
    }
    /// <summary>
    /// 输入数据解析出来到sr里
    /// </summary>
    /// <param name="sr"></param>
    /// <param name="byteTemp"></param>
    private static void DecodeData(string sr, byte[] byteTemp)
    {
        DateTime TimeStart = DateTime.Now;
        short sRightPack = 0;
        short[] ChipTime = new short[7];
        double Temperature;
        double Pressure, Altitude, GroundVelocity, GPSYaw, GPSHeight;
        long Longitude, Latitude;
        double[] LastTime = new double[10];



        float[] Data = new float[4];
        double TimeElapse = (DateTime.Now - TimeStart).TotalMilliseconds / 1000;

        Data[0] = BitConverter.ToInt16(byteTemp, 2);
        Data[1] = BitConverter.ToInt16(byteTemp, 4);
        Data[2] = BitConverter.ToInt16(byteTemp, 6);
        Data[3] = BitConverter.ToInt16(byteTemp, 8);
        sRightPack++;
        switch (byteTemp[1])
        {
            case 0x52:
                //Data[3] = Data[3] / 32768 * double.Parse(textBox9.Text) + double.Parse(textBox8.Text);
                Temperature = Data[3] / 100.0;
                Data[0] = Data[0] / 32768.0f * 2000;
                Data[1] = Data[1] / 32768.0f * 2000;
                Data[2] = Data[2] / 32768.0f * 2000;
                //sr.WX = Data[0];
                //sr.WY = Data[1];
                //sr.WZ = Data[2];
                //sr.WO = Data[3];
                if ((TimeElapse - LastTime[2]) < 0.1) return;
                LastTime[2] = TimeElapse;
                break;

            case 0x55:
                //sr.D0 = Data[0];
                //sr.D1 = Data[1];
                //sr.D2 = Data[2];
                //sr.D3 = Data[3];
                break;

            default:
                break;
        }
    }





    #endregion




}
}

